﻿using AuthCenter.API.Application.Command.Request;
using AuthCenter.Domain.Request;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;

namespace AuthCenter.API.Application.Handler.Request
{
    public class UpdStateRequestHandler : IRequestHandler<UpdStateRequestCommand, APIResult<int>>
    {
        private readonly IBaseRepository<RequestModel> requestRepo;
        private readonly IMapper mapper;

        public UpdStateRequestHandler(IBaseRepository<RequestModel> requestRepo,
                                      IMapper mapper)
        {
            this.requestRepo = requestRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<int>> Handle(UpdStateRequestCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = requestRepo.GetAll().FirstOrDefault(x => x.Id == request.Id);
            if (res == null)
            {
                result.Message = "找不到此编号";
                result.Code = APIEnum.Fail;
                return Task.FromResult(result);
            }
            var model = mapper.Map(request, res);
            int r = requestRepo.UpdateAsync(model).Result;
            if (r > 0)
            {
                result.Message = "修改申请成功";
                result.Code = APIEnum.Ok;
                result.Data = r;
            }
            else
            {
                result.Message = "修改申请失败";
                result.Code = APIEnum.Fail;
                result.Data = r;
            }
            return Task.FromResult(result);
        }
    }
}
